<?PHP

/**

*  Project Name:  NET114.COM

*  @package :  class.tool

*  @author  :  陈业华 <tcyh026@163.com> 

*  @date    : 2008.06.24

*  编码相关类

*/



class Encode

{
	public static $isOrder = false;
	
	/**

	*  实现JS的decodeURI函数

    *  @param $str (str,arr)

	*/

	public static function decodeURI($str)
	{
		if(is_array($str))
		{
			foreach($str as $k => $v)
			{
				$reStr[$k] = self::decodeURI($v);
			}
		}
		else
		{
			if(!self::$isOrder)
			{
				mb_detect_order("ASCII, EUC-CN, UTF-8, CP936");
				self::$isOrder = true;
			}
			$str = self::deUrl(urldecode($str));
			$str_code = mb_detect_encoding($str);
			if(in_array($str_code,array('EUC-CN','CP936')))
			{
				$restr = trim(iconv("utf-8","GBK",$str));
				if(strlen($str) == strlen($restr))
					return $str;
				if($restr && iconv("GBK","utf-8",$restr) == $str)
					return $restr;
				else
					return $str;
			}
			elseif($str_code)
			{
				if(function_exists('mb_convert_encoding'))
					$reStr = mb_convert_encoding($str,"GBK",$str_code);
				else
					$reStr = iconv($str_code,"GBK",$str);
			}
			if(empty($reStr))
			{
				if(mb_detect_encoding($str) != 'UTF-8')
					$reStr = $str;
				elseif(function_exists('mb_convert_encoding'))
					$reStr = mb_convert_encoding($str,"gbk","utf-8");
				else
					$reStr = iconv("utf-8","gbk",$str);
			}
		}
		return $reStr;
	}

	public static function getCoding($str,$encoding="ASCII, EUC-CN, UTF-8, CP936")
	{
		$str = urldecode($str);
		$str_code = mb_detect_encoding(urldecode($str),$encoding);
		if(in_array($str_code,array('EUC-CN','CP936')))
		{
			$restr = trim(iconv("utf-8","GBK",$str));
			if($restr && strlen($str) != strlen($restr) && iconv("GBK","utf-8",$restr) == $str) $str_code = 'UTF-8';
		}
		return $str_code;
	}

	/**
	*  实现JS的encodeURI函数
    *  @param $str (str,arr)
	*/
	public static function encodeURI($str)	
	{
		if(is_array($str))
		{
			foreach($str as $k => $v)
			{
				$reStr[$k] = self::encodeURI($v);
			}
		}
		else
		{
			if(function_exists('mb_convert_encoding'))
				$reStr = rawurlencode(mb_convert_encoding($str,"UTF-8","GBK"));
			else
				$reStr = urlencode(self::enUrl(iconv("gbk", "UTF-8", $str)));
		}
		return $reStr;
	}

	//从字符串编码转换
	public static function convert($vars,$from='gbk',$to='UTF-8')
	{
		if(is_array($vars))
		{
			foreach ($vars as $k => $v)
			{
				$vars[$k] = self::convert($v);
			}
		}
		else
		{
			if(function_exists('mb_convert_encoding'))
				$vars = mb_convert_encoding($vars,$to,$from);
			else
				$vars = iconv($from, $to, $vars);
		}
		return $vars;
	}

	//全角转半角
	public static function toDBC($str){
		return preg_replace('/\xa3([\xa1-\xfe])/e', 'chr(ord(\1)-0x80)', $str);
	}
	
	//半角转全角
	public static function toSBC($str){
		return preg_replace('/([\x0-\x7F])/e', 'chr(0xa3).chr(ord("\1")+0x80)', $str);
	}
	
	public static function enUrl($str,$type='en')
	{
		$fliter = array('-'=>'=2D','/'=>'=2F');
		if($type=='de')
		{
			$fliter = array_flip($fliter);
			return urldecode(strtr($str,$fliter));
		}
		return urlencode(strtr($str,$fliter));
	}

	public static function deUrl($str)
	{
		return self::enUrl($str,'de');
	}

	//取详细信息特征码，返回值 array(md5特征码,分词)
	public static function infoMd5Code($str,$sep=' ',$limit=30)
	{
                $ws = self::splitWords($str);
		$w=array();
		$wr=explode(' ',$ws);
		$i = 0;
		
		foreach ($wr as $item) {
			list($v1,$v2)=explode(':',$item);
			$v1 = trim($v1);
			#过滤单字的关键词和数字
			#过滤带“的”的词
			#TODO:过滤某些对重复信息判断没明显作用的词
			if(strlen($v1)>2 && !preg_match('/^[0-9.]+$/u',$v1) && strpos($v1,"的")===false)
			{
				$w[$v1]=array($v2,$i); 
				$volume[]  = $v2;
				$edition[] = $i++;
			}
		}
		if(is_array($w) && !empty($w))
		{
			array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $w);
			array_splice($w,$limit);
			
			ksort($w);
			$mdstr = implode($sep,array_keys($w));
			$results = array(md5($mdstr),$mdstr);
			return $results;
		}
		return false;
	}

	/**
	 * 分词
	 * 
	 * @param string $str 需要分词的内容
	 * @param mixed $type 默认返回字符串“word:volume word:volume”.等于array，则返回数组array(word=>volume),并按volume降序排列
	 */
	public static function splitWords($str,$type=null)
	{
		$url = 'http://192.168.1.67:7777/?m=4';
		//$url = 'http://192.168.1.131:7777/?m=4';
		$referrer=$_SERVER["SCRIPT_URI"];
		$URL_Info=parse_url($url);
		if (!isset($URL_Info["port"])) $URL_Info["port"]=80;
		$str = str_replace("&nbsp;","",$str);#除去空格的html实体字
		$content=strip_tags($str);
		$content=urlencode($content);
		$ws='';
		$request='';
		$request.="POST /?m=4 HTTP/1.1\r\n";
		$request.="Content-type: application/x-www-form-urlencoded\r\n";
		$request.= "User-Agent: {$_SERVER[HTTP_USER_AGENT]}\r\n";
		$request.="Host: ".$URL_Info["host"]."\r\n";
		$request.="Content-length: ".strlen($content)."\r\n";
		$request.="Connection: Close\r\n";
		$request.="Cache-Control: no-cache\r\n";
		$request.="\r\n".$content;
	
		$fp = @fsockopen($URL_Info["host"], $URL_Info["port"], $errno, $errstr, 2);
		if(!$fp)
		{
			return false;
		} else {
			stream_set_timeout($fp,2);
			if (fwrite($fp, $request))
			{
				$ws='';
				$header = "not yet";
				while (!feof($fp)) {
					$line=fgets($fp,128);
					if ($line=="\r\n" && $header=="not yet") $header = "passed";
					if ($header=="passed") $ws.=$line;
				}
			}
			fclose($fp);
		}
		#TODO:这里需要做处理，过滤单字等
		if($type == 'array')
		{
			$wr=explode(' ',$ws);
			foreach ($wr as $item) {
				list($v1,$v2)=explode(':',$item);
				$v1 = trim($v1);
				if(strlen($v1)>1 && !preg_match('/^[0-9.]+$/u',$v1))
				{
					$tmpArr[$v1] = $v2;
				}
			}
			if($tmpArr)
			{
				arsort($tmpArr);
				$ws = $tmpArr;
			}
		}
		return $ws;
	}
}
?>